package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private  ReportService reportService;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * - 营业额指订单状态为已完成的订单金额合计
     * - 基于可视化报表的折线图展示营业额数据，X轴为日期，Y轴为营业额
     * - 根据时间选择区间，展示每天的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
//    @Override
//    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
//
////        // 1. 拿到起止时间
////        List<LocalDate> dataList = new ArrayList<>();
////        dataList.add(begin);
////        while (!begin.equals(end)) {
////            begin = begin.plusDays(1);
////            dataList.add(begin);
////        }
////
////        // 2. 用每天的时间查询营业额
////        List<Double> turnoverList = new ArrayList<>();
////        for (LocalDate localDate : dataList) {
////            // 将日期转换为当天的最小和最大时间
////            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
////            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
////
////            // 查询当天的营业额
////            Double turnover = orderMapper.turnoverStatistics(beginTime, endTime, Orders.COMPLETED);
////
////            // 如果营业额为空，则设置为0
////            turnover = turnover == null ? 0.0 : turnover;
////            turnoverList.add(turnover);
////        }
////
////        // 3. 组装返回
////        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
////        turnoverReportVO.setDateList(StringUtils.join(dataList, ","));
////        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));
////
////        return turnoverReportVO;
//
//    }

//    /**
//     * 用户统计
//     *
//     * @param begin
//     * @param end
//     * @return
//     */
//    @Override
//    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
//        // 1. 先取到每天的日期
//        List<LocalDate> dataList = new ArrayList<>();
//        dataList.add(begin);
//
//        while (!begin.equals(end)) {
//            begin = begin.plusDays(1);
//            dataList.add(begin);
//        }
//
//        // 2. 查询每天的新增用户数和总用户数
//        List<Integer> newUserList = new ArrayList<>();
//        List<Integer> allUserList = new ArrayList<>();
//        for (LocalDate localDate : dataList) {
//            // 将日期转换为当天的最小和最大时间
//            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
//            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
//
//            // 查询当天的新增用户数和总用户数
//            Integer newUser = userMapper.count(beginTime, endTime);
//            Integer allUser = userMapper.count(null, endTime);
//
//            newUserList.add(newUser);
//            allUserList.add(allUser);
//        }
//
//        // 3. 组装返回
//        return UserReportVO.builder()
//                .totalUserList(StringUtils.join(allUserList, ","))
//                .dateList(StringUtils.join(dataList, ","))
//                .newUserList(StringUtils.join(newUserList, ","))
//                .build();
//    }

//    /**
//     * 订单统计
//     *
//     * @param begin
//     * @param end
//     * @return
//     */
//    @Override
//    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
//
//        //先取到每天的日期
//        List<LocalDate> dataList = new ArrayList<>();
//        dataList.add(begin);
//        while (!begin.equals(end)) {
//            begin = begin.plusDays(1);
//            dataList.add(begin);
//        }
//        //查询每天有效的订单数
//        List<Integer> validOrderCountList = new ArrayList<>();
//        //查询总的
//        List<Integer> orderCountList = new ArrayList<>();
//
//        for (LocalDate localDate : dataList) {
//
//            //拿到每天最早的时间和最晚的时间
//            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
//            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
//
//            Integer orderCount = orderMapper.count(beginTime, endTime,Orders.COMPLETED);
//            Integer validCount = orderMapper.count(beginTime, endTime,null);
//            orderCountList.add(orderCount);
//            validOrderCountList.add(validCount);
//
//
//        }
//        //reduce做运算 integer 返回值类型，sum 运算符
//        Integer validCount = validOrderCountList.stream().reduce(Integer::sum).get();
//        Integer orderCount = orderCountList.stream().reduce(Integer::sum).get();
//
//        //完成率
//        Double orderCompletionRate = 0.0;
//        if (orderCount != 0) {
//            orderCompletionRate = validCount.doubleValue() / orderCount;
//        }
//        OrderReportVO build = OrderReportVO.builder()
//                .dateList(StringUtils.join(dataList, ","))
//                .orderCompletionRate(orderCompletionRate)
//                .orderCountList(StringUtils.join(orderCountList, ","))
//                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
//                .validOrderCount(validCount)
//                .totalOrderCount(orderCount)
//                .build();
//        return build;
//    }

//    /**
//     * 查询top10
//     * @param begin
//     * @param end
//     * @return
//     */
//    @Override
//    public SalesTop10ReportVO top10Statistics(LocalDate begin, LocalDate end) {
//
//        // 1. 将起止时间转换为LocalDateTime类型
//        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
//        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
//
//        // 2. 查询销售前十的商品
//        List<GoodsSalesDTO> list=orderMapper.top10(beginTime,endTime);
//
//        // 3. 将商品名称和销售数量分别存入两个列表中
//        List<String> nameList = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
//        List<Integer>  numberList = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
//
//        // 4. 组装返回
//        return SalesTop10ReportVO.builder()
//                .nameList(StringUtils.join(nameList,",")) // 将商品名称列表转换为字符串
//                .numberList(StringUtils.join(numberList,",")) // 将销售数量列表转换为字符串
//                .build();
//
//    }


    /**
     * 根据时间区间统计营业额（课程导入）
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);//日期计算，获得指定日期后1天的日期
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin",beginTime);
            map.put("end", endTime);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        //数据封装
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = getUserCount(beginTime, endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /**
     * 根据时间区间统计订单数量(导入)
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
        //每天有效订单数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询每天的总订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer orderCount = reportService.getOrderCount(beginTime, endTime, null);

            //查询每天的有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = ?
            Integer validOrderCount = reportService.getOrderCount(beginTime, endTime, Orders.COMPLETED);

            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }

        //时间区间内的总订单数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    @Override
    public Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("status", status);
        map.put("begin",beginTime);
        map.put("end", endTime);
        return orderMapper.countByMap(map);
    }
    /**
     * 查询指定时间区间内的销量排名top10（导入）
     * @param begin
     * @param end
     * @return
     * */

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出近30天的运营数据
     * @param httpServletResponse
     */
    @Override
    public void export(HttpServletResponse httpServletResponse) {

      //查询30天的
        LocalDate begin = LocalDate.now().minusDays(30);
        //查询第一天
        LocalDate end = LocalDate.now().minusDays(1);
        //查询运营数据，提供给excel模板
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //取到类  类加载器 取到输入流
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            //把日期填充到第2行
            sheet1.getRow(1).getCell(1).setCellValue(begin+"------------"+end);
            sheet1.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(1);
                //查询当天的数据
                 businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
                XSSFRow row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            }
            //通过输出流讲文件下载到客户端浏览器中
            ServletOutputStream out = httpServletResponse.getOutputStream();
            excel.write(out);

            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }



    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    public Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

}
